<template>
  <div class="type-show" :class="{ shake: isShaking }">
    <!-- 顶部导航栏 -->
    <div class="header-nav">
      <div class="header-left">
        <div class="title-bar"></div>
        <span class="page-title">财务类别</span>
      </div>
      <div class="header-right">
        <el-button icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
        <el-button icon="el-icon-arrow-left">返回</el-button>
      </div>
    </div>

    <!-- 数据筛选 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="类别名称:">
            <el-input v-model="formInline.Name" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">数据列表</div>
        <div class="action-buttons">
          <el-button icon="Plus" @click="handleAdd">新增</el-button>
          <el-button icon="Edit" @click="handleEdit">编辑</el-button>
          <el-button icon="Delete" @click="handleDelete">删除</el-button>
          <el-button icon="Refresh" @click="handleRefresh">刷新</el-button>
          <el-button icon="Upload" @click="handleExport">导出</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="number" label="类别编号" width="200" />
        <el-table-column prop="name" label="类别名称" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="220">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="190">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="Edit(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="isEditMode ? '编辑类别' : '新增类别'" v-model="dialogVisible" width="600px">
      <el-form :model="dialogForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类别编号:">
              <el-input v-model="dialogForm.number" placeholder="不可填写，自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别名称:">
              <el-input v-model="dialogForm.name" placeholder="请输入类别名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:">
          <el-input v-model="dialogForm.note" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { FinanceRed, FinanceWrite } from '@/http/axiosHelper'
import { id } from 'element-plus/es/locales.mjs'
  import { statementRed } from '@/http/axiosHelper'
//导出
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await FinanceRed({
            url: '/api/Sort/GetSortShow', // 后端接口地址
            method: 'get',
            params: {
              Name: formInline.Name
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '财务类别.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '可出库存.xlsx';
}
//查询显示
const formInline = reactive({
  Name: '',
})
const onSubmit = () => {
  console.log('onSubmit 被调用');
  FinanceRed.get("/api/Sort/GetSort", {
    params: {
      Name: formInline.Name
    }
  }).then(res => {
    console.log('获取到的表格数据:', res.data.data);
    tableData.value = res.data.data
  })
}
//删除
const handleClick = (id) => {
  ElMessageBox.confirm(
    '该操作将删除该数据, 确定要删除吗?',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户点击确定，调用后端删除接口
      FinanceWrite.delete("/api/Sort/DelSort", { data: { id: id } })
        .then(res => {
          ElNotification({
            title: '数据删除成功',
            message: '数据删除成功',
            type: 'success',
            position: 'bottom-right'
          });
          onSubmit(); // 刷新表格
        })
        .catch(() => {
          ElNotification({
            title: '删除失败',
            message: '删除操作未成功',
            type: 'error',
            position: 'bottom-right'
          });
        });
    })
    .catch(() => {
      // 用户点击取消，无需操作
    });
}

const tableData = ref([])
onMounted(()=>
{
  onSubmit();
})


const dialogVisible = ref(false)
const dialogForm = reactive({
  id: '',
  number: '',
  name: '',
  note: ''
})

const isEditMode = ref(false);

const Edit = (row) => {
  console.log('编辑行数据:', row); // 调试信息
  isEditMode.value = true;
  
  // 重置表单数据
  dialogForm.id = '';
  dialogForm.number = '';
  dialogForm.name = '';
  dialogForm.note = '';
  
  // 填充表单数据
  dialogForm.id = row.id;
  dialogForm.number = row.number ? String(row.number) : '';
  dialogForm.name = row.name || '';
  dialogForm.note = row.note || '';
  
  console.log('填充后的表单数据:', dialogForm); // 调试信息
  dialogVisible.value = true;
};

// 新增按钮
const handleAdd = () => {
  isEditMode.value = false;
  dialogForm.id = '';
  const now = new Date()
  const pad = n => n.toString().padStart(2, '0')
  // 只用年月日时，长度10位
  dialogForm.number = `${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}${pad(now.getHours())}`
  dialogForm.name = ''
  dialogForm.note = ''
  dialogVisible.value = true
}

// 确定按钮
const handleDialogConfirm = () => {
  if (!dialogForm.name) {
    ElMessage.warning('请输入类别名称')
    return
  }
  if (isEditMode.value) {
    // 编辑
    FinanceWrite.put('/api/Sort/UpdateSort', {
      id: dialogForm.id,
      number: dialogForm.number,
      name: dialogForm.name,
      note: dialogForm.note
    }).then(res => {
      ElMessage.success('修改成功')
      dialogVisible.value = false
      onSubmit()
    }).catch(() => {
      ElMessage.error('修改失败')
    })
  } else {
    // 新增
    FinanceWrite.post('/api/Sort/AddSort', {
      number: dialogForm.number,
      name: dialogForm.name,
      note: dialogForm.note
    }).then(res => {
      ElMessage.success('新增成功')
      dialogVisible.value = false
      onSubmit()
    }).catch(() => {
      ElMessage.error('新增失败')
    })
  }
}

const formatDate = (val) => {
  if (!val) return '';
  // 只替换第一个T为一个空格
  return String(val).replace('T', ' ');
}

const selectedRows = ref([])
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

const handleDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条数据吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 调用后端批量删除接口
    const ids = selectedRows.value.map(item => item.id)
    FinanceWrite.delete('/api/Sort/BeachDelete', {
      data:{id:ids.join(',')}
    })
      .then(res => {
        ElNotification({
          title: '批量删除成功',
          message: '已成功删除所选数据',
          type: 'success',
          position: 'bottom-right'
        })
        onSubmit()
      })
      .catch(() => {
        ElNotification({
          title: '批量删除失败',
          message: '删除操作未成功',
          type: 'error',
          position: 'bottom-right'
        })
      })
  })
  .catch(() => {})
}

const isShaking = ref(false)

const handleRefresh = () => {
  console.log('刷新按钮被点击');
  formInline.Name = '';
  onSubmit();

  // 触发 shake 动画
  isShaking.value = true
  setTimeout(() => {
    isShaking.value = false
  }, 500) // 动画持续 500ms
}

// 重置筛选条件
const handleReset = () => {
  formInline.Name = '';
  onSubmit();
}
</script>

<style>
/* 顶部导航栏样式 */
.header-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.title-bar {
  width: 4px;
  height: 20px;
  background: #409eff;
  margin-right: 12px;
  border-radius: 2px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 筛选卡片样式 */
.filter-card {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.filter-content {
  padding: 20px;
}

/* 表格卡片样式 */
.table-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.table-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 按钮样式调整 - 统一为白色背景，更小尺寸 */
.action-buttons .el-button {
  background-color: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 6px 12px;
  font-size: 12px;
  height: 28px;
}

.action-buttons .el-button--primary {
  background-color: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.action-buttons .el-button:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #606266;
}

.action-buttons .el-button--primary:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #606266;
}

/* 确保图标颜色与文字颜色一致 */
.action-buttons .el-button .el-icon {
  color: #606266;
}

.action-buttons .el-button:hover .el-icon {
  color: #606266;
}

/* 表单样式调整 */
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 表格样式 */
.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 12px 8px;
}

/* 动画效果 */
.type-show.shake {
  animation: shake 0.5s;
}

@keyframes shake {
  0% { transform: translateX(0); }
  20% { transform: translateX(-10px); }
  40% { transform: translateX(10px); }
  60% { transform: translateX(-10px); }
  80% { transform: translateX(10px); }
  100% { transform: translateX(0); }
}

/* 卡片内容区域 */
.el-card__body {
  padding: 0;
}

/* 按钮样式调整 */
.el-button {
  border-radius: 4px;
}

/* 表格操作列按钮样式 */
.el-table .el-button--small {
  padding: 4px 8px;
  font-size: 12px;
}
</style>
